package com.lagou.classLoader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class MyClassLoader extends ClassLoader {
    /**
     * webapps绝对路径
     */
    private String webappsPath;

    public MyClassLoader(String webappsPath) {
        this.webappsPath = webappsPath;
    }

    @Override
    public Class<?> findClass(String name) {
        //获取字节码文件的完整路径
        String classPath = webappsPath + "/" + name + ".class";
        Class<?> clazz = null;
        BufferedInputStream bos = null;
        ByteArrayOutputStream baos = null;
        try {
            //输入流
            bos = new BufferedInputStream(new FileInputStream(classPath));
            //缓冲数组buf
            byte[] buf = new byte[1024];
            int len;
            //输出流
            baos = new ByteArrayOutputStream();
            //循环读取，写入baos中的字节数组
            while ((len = bos.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            //获取字节数组
            byte[] bytes = baos.toByteArray();
            //defineClass
            clazz = defineClass(null, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭流
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (clazz == null) {
            throw new RuntimeException("Class Not Found");
        } else {
            return clazz;
        }
    }

}
